package com.mes.handler.plan;

import com.basis.utils.HibernateDao;
import com.wms.entity.WmsMaterialList;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.model.common.enterprise.Warehouse;
import org.openbravo.model.common.plm.Product;
import java.util.List;
import java.util.Map;

/**
 * 作业工单生成领料单
 */
public class JobOrderGenerateMaterialHandler extends BaseActionHandler {
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		try {
			//设置最高权限
			OBContext.setAdminMode();
			JSONObject reqData = new JSONObject(data);

			String[] ids = reqData.getString("ids").split(",");
			String sendTime = reqData.getString("sendTime");
			String description = reqData.getString("description");

			createMaterial(ids, sendTime, description);

			OBDal.getInstance().commitAndClose();

			jsonRep.put("result", true);
			jsonRep.put("msg", "生成领料单成功！");
		} catch (Exception e) {
			e.printStackTrace();
			OBDal.getInstance().rollbackAndClose();
			try {
				jsonRep.put("result", false);
				jsonRep.put("msg", e.getMessage());
			} catch (Exception ex) {
			}
		} finally {
			OBContext.restorePreviousMode();
		}
		return jsonRep;
	}

	/**
	 * 派工到飞织机
	 * @param ids
	 */
	private void createMaterial(String []ids, String sendTime, String description) {
		String sql = "select jpb.m_product_id, jp.emes_size_id, jpb.emes_color_id, jpb.emes_shape_id, \n" +
				"    (select pis.qty from emes_pbom p, emes_pbom_item pi \n" +
				"      where p.emes_pbom_id = pi.emes_pbom_id\n" +
				"       and pi.emes_pbom_item_id = pis.emes_pbom_item_id\n" +
				"      and pis.emes_color_id = jpb.emes_color_id\n" +
				"      and pis.emes_size_id = jp.emes_size_id\n" +
				"      and pis.m_product_id = jpb.m_product_id\n" +
				"      and mo.m_product_id = p.m_product_id) qty\n" +
				"  from emeso_job_plan_bom jpb, emeso_job_plan jp, emeso_manuorder mo\n" +
				" where jpb.emeso_job_plan_id = jp.emeso_job_plan_id \n" +
				"  and jpb.emes_shape_id is not null\n" +
				"  and jp.emeso_manuorder_id = mo.emeso_manuorder_id\n" +
				"  and mo.emeso_manuorder_id = ?";

		WmsMaterialList head = new WmsMaterialList();
		head.setWarehouse(OBDal.getInstance().get(Warehouse.class, "1E0A69B1B7BB4EECB232D6989684C4D7"));

		String codes = "";

		List<Map<String, Object>> result = null;
		for (String id : ids) {
			result = HibernateDao.query(sql, id);


		}
	}

	/**
	 * 获取楦头物料ID
	 * @param product
	 * @param xuanType
	 * @return
	 */
	private Product getXuantou(String product, String xuanType) {

		return null;
	}
}